<?php

  /**
   * Tags
   *
   * Класс виджета, выводящего теги
   */

  class Tags extends XMLWidget
  {
    /**
     * тип тегов (теги, рубрики или все сразу - "облако")
     *
     * @var string
     */
    public $type = "cloud";

    /**
     * запустить виджет
     *
     * @return void
     * @access public
     */
    public function run()
    {
      $tags = TagName::model()->{$this->type}()->with("tags")->findAll();
      ($isRubric = !strcasecmp($this->type, TagName::RUBRIC)) or ($tags = array_filter($tags, create_function('TagName $tag', 'return $tag->getCount();')));

      self::openNode($type = $this->type."s", array("total" => count($tags)));

      /** @var $db CDbConnection */
      $db = $this->getController()->getApp()->getDb();

      /** @var $item TagName */
      foreach ($tags as $item)
      {
        self::openNode($item->type, array("id" => $id = $item->id, "count" => $item->getCount()));
        self::htmlNode("name", $item->name);

        if ($isRubric)
        {
          $subtags = $db->createCommand(
            "select `id`,`name` from `tag_names` where `type`='tag' and `id` in(".
              "select `tag_id` from `tags` where `rec_id` in(".
                "select `rec_id` from `tags` where `tag_id`='$id'))"
          )->queryAll();

          if (!empty($subtags))
          {
            self::openNode("tags");
              array_walk($subtags, create_function('array &$t', 'XMLWidget::htmlNode("tag", $t["name"], array("id" => $t["id"]));'));
            self::closeNode("tags");
          }
        }

        self::closeNode($item->type);
      }

      self::closeNode($type);
    }
  }

?>